package com.steshov.el.dao;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.steshov.el.entity.User;
import com.steshov.el.util.App;
import com.steshov.el.util.DataBaseException;

@Component
public class UserDao {

	@Autowired
	SessionFactory sessionFactory;

	public UserDao() {
	}

	private Session getSession() {
		return getSessionFactory().getCurrentSession();
	}

	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public User authorized(String login, String pass)
			throws DataBaseException {
		User user = null;
		try {
			Criteria criteria = getSession().createCriteria(User.class);
			criteria.add(Restrictions.like("login", login)).add(
					Restrictions.like("password", pass));
			user = (User) criteria.uniqueResult();
		} catch (Exception e) {
			App.log.error(e);
			throw new DataBaseException(e);
		}

		return user ;
	}

	@Transactional
	public Boolean createUser(User user) throws DataBaseException {
		try {
			getSession().persist(user);
			return true;
		} catch (Exception e) {
			App.log.error(e);
			throw new DataBaseException(e);
		}
	}

	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public User getUserByLogin(String login) throws DataBaseException {
		Criteria criteria=null;
		User user = null;
		try {
			 criteria = getSession().createCriteria(User.class);
			 criteria.add(Restrictions.like("login",login));
			user = (User) criteria.uniqueResult();
		} catch (Exception e) {
			App.log.error(e);
			throw new DataBaseException(e);
		}
		return user;
	}
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
